//
//  HWTweetcommentView.m
//  HomeWork
//
//  Created by apple on 2017/10/25.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "HWTweetcommentView.h"
#import "HWTweetCommentCell.h"
#import "HWTweetCommentViewModel.h"
@interface HWTweetcommentView()<UITableViewDelegate, UITableViewDataSource>
/** 表视图 */
@property (strong, nonatomic) UITableView *tableView;
/** 总长度 */
@property (assign, nonatomic) CGFloat tableHeight;


@end

@implementation HWTweetcommentView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews{
    
    UITableView *tableView = [[UITableView alloc] init];
    self.tableView = tableView;
    tableView.scrollEnabled = NO;
    [self addSubview:tableView];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.delegate = self;
    tableView.dataSource = self;
    
}

#pragma mark - 代理 && 数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.comments.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HWTweetCommentCell *cell = [HWTweetCommentCell cellWithTableView:tableView];
    cell.comment = self.comments[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat rowHeight = [HWTweetCommentCell heightWithModel:self.comments[indexPath.row]];
    return rowHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HWTweetCommentUser *userInfo = self.comments[indexPath.row];
    [self.viewModel.replyCmtSubject sendNext:userInfo];
}

- (void)setComments:(NSArray *)comments{
    _comments = comments;
    self.tableHeight = 0;
    
    for (HWTweetCommentUser *comment in comments) {
        CGFloat rowHeight = [HWTweetCommentCell heightWithModel:comment];
        self.tableHeight += rowHeight;
    }
    
    [self.tableView reloadData];
    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];
}

- (void)updateConstraints{
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
        make.height.mas_equalTo(self.tableHeight);
    }];
    [self mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.tableHeight);
    }];
    [super updateConstraints];
}


@end
